import 'dart:convert';
import 'dart:io';

/// IP操作工具类,使用方法如下:
///
/// IpUtil.ipV4().then((ip) {
///
///     print("ip地址: $ip");
///
/// });
///
/// IpUtil.ipInternet((ip) {
///
///     print("Internet IP: $ip");
///
/// });
class IpUtil {
  /// 获取IPV4地址
  /// 局域网内返回的是局域网地址
  static Future<String> ipV4() async {
    // 获取IP地址
    var interfaceList = await NetworkInterface.list();
    String ipStr = "127.0.0.1";
    for (var model in interfaceList) {
      if (model.addresses.first.type == InternetAddressType.IPv4) {
        ipStr = model.addresses.first.address;
      }
    }
    return Future.value(ipStr);
  }

  /// 通过网页链接[https://www.ip.cn/]获取,从网页中通过正则表达式获取到IP地址
  /// [action] 回调函数,异常时返回null
  static ipInternet(void action(String? ip)) async {
    try {
      var ipRegexp = RegExp(
          r'((?:(?:25[0-5]|2[0-4]\d|(?:1\d{2}|[1-9]?\d))\.){3}(?:25[0-5]|2[0-4]\d|(?:1\d{2}|[1-9]?\d)))');
      var url = 'https://www.ip.cn/';
      var client = HttpClient();
      var request = await client.getUrl(Uri.parse(url));
      var reponse = await request.close();
      reponse.transform(utf8.decoder).forEach((line) {
        ipRegexp.allMatches(line).forEach((match) {
          action(match.group(0));
        });
      });
    } catch (err) {
      print(err);
      return null;
    }
  }
}
